import 'package:bt_dsp_88/model/model_extension.dart';
import 'package:flutter/material.dart';

import '../../model/model.dart';
import '../../model/model_default.dart';
import '../../notify/globalState.dart';
import '../../tool/assets.dart';
import 'pass_botton.dart';

class PassTypeView extends StatefulWidget {
  Passmodel pass;
  void Function(Passmodel, String) onClick;
  PassTypeView({super.key, required this.pass, required this.onClick});

  @override
  State<PassTypeView> createState() => _PassTypeViewState();
}

class _PassTypeViewState extends State<PassTypeView> {
  final LayerLink _layerLink = LayerLink();
  OverlayEntry? _overlayEntry;
  bool _isDropdownOpen = false;
  final GlobalKey _buttonKey = GlobalKey(); // 使用 GlobalKey 来获取按钮宽度
  List<String> get _list {
    return [
      '${widget.pass.name}',
      '${widget.pass.type?.name}',
      'ByPass',
      'Reset'
    ];
  }

  ///======================弹出下拉框   start==============================
  ///弹出下拉框
  void _openDropdown() {
    if (_isDropdownOpen) {
      _closeDropdown();
      return;
    }

    final RenderBox buttonRenderBox =
        _buttonKey.currentContext?.findRenderObject() as RenderBox;
    final buttonSize = buttonRenderBox.size;
    final buttonPosition = buttonRenderBox.localToGlobal(Offset.zero);
    _overlayEntry = OverlayEntry(
      builder: (context) {
        return Positioned(
          width: buttonSize.width,
          top: buttonPosition.dy + buttonSize.height,
          left: buttonPosition.dx,
          child: AnimatedContainer(
            duration: const Duration(milliseconds: 300),
            curve: Curves.easeOut,
            height: 75 * GlobalConfig.scaleH,
            decoration: BoxDecoration(
              color: Color_bg_view,
              borderRadius: const BorderRadius.all(Radius.circular(5)),
              border: Border.all(color: Color_border, width: 0.5),
              boxShadow: const [
                BoxShadow(color: Colors.black26, blurRadius: 8)
              ],
            ),
            child: ListView(
              padding: EdgeInsets.zero,
              children: defualt_type_list.asMap().entries.map(($0) {
                return SizedBox(
                  height: 26 * GlobalConfig.scaleH,
                  child: Center(
                    child: InkWell(
                      onTap: () {
                        _closeDropdown();

                        ///选择pass的类型
                        widget.pass.type = defualt_type_list[$0.key].copy;
                        widget.onClick(widget.pass, 'passtype');
                      },
                      child: Text($0.value.name,
                          style: const TextStyle(
                              fontSize: 12, color: Colors.black),
                          textAlign: TextAlign.center,
                          maxLines: 1),
                    ),
                  ),
                );
              }).toList(),
            ),
          ),
        );
      },
    );

    Overlay.of(context).insert(_overlayEntry!);
    _isDropdownOpen = true;
  }

  void _closeDropdown() {
    _overlayEntry?.remove();
    _overlayEntry = null;
    _isDropdownOpen = false;
  }

  @override
  void initState() {
    super.initState();
    globalState.addListener((data) {
      if (data.key == '隐藏下拉框') {
        _closeDropdown();
      }
    });
  }

  @override
  void dispose() {
    _closeDropdown();
    super.dispose();
  }

  ///======================弹出下拉框    end ==============================

  @override
  Widget build(BuildContext context) {
    _closeDropdown();
    return LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constrains) {
      return SizedBox(
        height: 45 * GlobalConfig.scaleH,
        child: Stack(
          children: [
            ///黑线
            Positioned(
                left: 0,
                right: 0,
                top: 29.5 * GlobalConfig.scaleH,
                child: Container(
                    color: text_color(widget.pass, selectColor: Colors.black),
                    height: 1)),

            ///四个按钮
            Positioned(
              left: 0,
              right: 0,
              top: 15 * (GlobalConfig.scaleH + 0.1),
              height: 30 * (GlobalConfig.scaleH - 0.1),
              child: GridView.extent(
                maxCrossAxisExtent: 70,
                mainAxisSpacing: (constrains.maxWidth - 70 * 4) / 3.0,
                crossAxisSpacing: (constrains.maxWidth - 70 * 4) / 3.0,
                childAspectRatio: 70 / 30.0 / (GlobalConfig.scaleH - 0.1),
                physics: const NeverScrollableScrollPhysics(),
                children: _list.asMap().entries.map(($0) {
                  ///下拉框按钮
                  if ($0.key == 1) {
                    bool enable = widget.pass.enable && widget.pass.select;
                    Color dynamicColor =
                        enable ? Colors.black : Color_disEnable;
                    return CompositedTransformTarget(
                      link: _layerLink,
                      child: PassBotton(
                        globalkey: _buttonKey,
                        title: $0.value,
                        textColor: dynamicColor,
                        icon: Image.asset(
                            _isDropdownOpen
                                ? assets.arrow_up
                                : assets.arrow_down,
                            width: 10,
                            height: 10,
                            color: dynamicColor),
                        padding: const EdgeInsets.only(left: 2, right: 2),
                        groundColor: Color_bg_view,
                        borderColor: dynamicColor,
                        enable: enable,
                        onClick: _openDropdown,
                      ),
                    );
                  } else {
                    bool enable = false;
                    Color bgColor = Color_bg_view;

                    if ($0.key == 0) {
                      enable = widget.pass.enable;
                      bgColor = enable &&
                              widget.pass.select &&
                              widget.pass.isBypass == false
                          ? Color_theme
                          : Color_bg_view;
                    } else if ($0.key == 2) {
                      enable = widget.pass.enable && widget.pass.select;
                      bgColor = enable && widget.pass.isBypass
                          ? Color_theme
                          : Color_bg_view;
                    } else if ($0.key == 3) {
                      enable = widget.pass.enable && widget.pass.select;
                      bgColor = Color_bg_view;
                    }
                    Color borderColor = enable ? Colors.black : Color_disEnable;

                    return PassBotton(
                      title: $0.value,
                      textColor: borderColor,
                      padding: const EdgeInsets.only(left: 2, right: 2),
                      groundColor: bgColor,
                      borderColor: borderColor,
                      enable: enable,
                      onClick: $0.key == 3
                          ? null
                          : () => widget.onClick(widget.pass, $0.value),
                      onLongPress: $0.key != 3
                          ? null
                          : () => widget.onClick(widget.pass, $0.value),
                    );
                  }
                }).toList(),
              ),
            ),
          ],
        ),
      );
    });
  }
}
